package com.pfzy.liveeventbusdemo.activity

import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import com.jeremyliao.liveeventbus.LiveEventBus

/**
 * 测试
 */
class TestActivity : AppCompatActivity() {
    var receiveMsgSetBeforeOnCreate = false
    var strResult: String? = null
    var receiveCount = 0
    private val observer: Observer<String> =
        Observer { s -> strResult = s }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        LiveEventBus
            .get(KEY_TEST_OBSERVE, String::class.java)
            .observe(this, { s -> strResult = s })
        LiveEventBus
            .get(KEY_TEST_OBSERVE_FOREVER, String::class.java)
            .observeForever(observer)
        LiveEventBus
            .get(KEY_TEST_MULTI_THREAD_POST, String::class.java)
            .observe(this, { receiveCount++ })
        LiveEventBus
            .get(KEY_TEST_BROADCAST_VALUE, String::class.java)
            .observe(this, { s -> strResult = s })
        testMessageSetBeforeOnCreate()
    }

    private fun testMessageSetBeforeOnCreate() {
        LiveEventBus.get(
            KEY_TEST_MSG_SET_BEFORE_ON_CREATE,
            String::class.java
        ).post("msg_set_before")
        LiveEventBus
            .get(KEY_TEST_MSG_SET_BEFORE_ON_CREATE, String::class.java)
            .observe(this, { s ->
                receiveMsgSetBeforeOnCreate = true
                strResult = s
            })
    }

    override fun onDestroy() {
        super.onDestroy()
        LiveEventBus
            .get(KEY_TEST_OBSERVE_FOREVER, String::class.java)
            .removeObserver(observer)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == IpcTestActivity.RESULT_CODE) {
            strResult = data!!.getStringExtra(IpcTestActivity.RESULT_EXTRA_KEY)
        }
    }

    companion object {
        const val KEY_TEST_OBSERVE = "key_test_observe"
        const val KEY_TEST_OBSERVE_FOREVER = "key_test_observe_forever"
        const val KEY_TEST_MULTI_THREAD_POST = "key_test_multi_thread_post"
        const val KEY_TEST_MSG_SET_BEFORE_ON_CREATE = "key_test_msg_set_before_on_create"
        const val KEY_TEST_BROADCAST_VALUE = "key_test_broadcast_value"
    }
}